package rpt.yto.action;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.tomcat.util.http.Cookies;
import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import rpt.yto.flex.remote.data.dao.IUserDAO;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

	private static final long serialVersionUID = -6589503077592404581L;

	private HttpServletResponse response;
	private HttpServletRequest request;
	
	private static ApplicationContext context;
	private static IUserDAO userDAO;
	
	static {
		context = new ClassPathXmlApplicationContext("applicationContext.xml");
		userDAO = (IUserDAO) context.getBean("userDAO");
	}
	
	public String loginLog() throws Exception {
		
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		
		AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
		
		if(principal == null) 
			return null;
		
		String usercode = principal.getName();
		request.getSession().setAttribute("user", usercode);
		
		Map<String , Object> userMap = userDAO.queryUserByCode(usercode);
		
		if(userMap == null) {
			userDAO.saveUser(usercode);
			response.sendRedirect("/hrrpt/error.jsp");
			return null;
		}
		
		if(!Boolean.valueOf(String.valueOf(userMap.get("isenable".toUpperCase())))) {
			response.sendRedirect("/hrrpt/error.jsp");
			return null;
		}
		Cookie[] cookies = request.getCookies();
		for(Cookie cookie : cookies ) {
			if("islogin".equals(cookie.getName())) {
				cookie.setValue("true");
				response.addCookie(cookie);
				response.sendRedirect("");
				return null;
			}
		}
		
		response.sendRedirect("rpt/");
		return null;
	}
	
}
